package nin.ja;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.opengl.GLU;
import android.opengl.GLSurfaceView.Renderer;
import android.util.Log;

public class GameRenderer extends GLSurfaceView implements Renderer{
	
	private int width;
	private int height;
	private Context context;
	private RenderQueue.RenderableObject[] queue;
	
	public static Object drawLock;
	
	public GameRenderer(Context context, int width, int height){
		super(context);
		this.setRenderer(this);
		this.context = context;
		this.width = width;
		this.height = height;
		this.requestFocus();
		this.setFocusableInTouchMode(true);
		queue = new RenderQueue.RenderableObject[64];
		for(int i = 0; i < 64; ++i){
			queue[i] = null;
		}
		drawLock = new Object();
		
		Log.v("GameRednerer", "GameRenderer loaded");
	}
	
	@Override
	public void onDrawFrame(GL10 gl) {
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);	
		gl.glLoadIdentity();
		
		synchronized(drawLock){
			//Log.v("GameRenderer", "GameRenderer owns drawLock");
			for(int i = 0; i < queue.length; ++i){
				if(queue[i] != null){
					//Log.v("GameRenderer", "Position: " + queue[i].position.getX() + ", " +  queue[i].position.getY());
					gl.glTranslatef(queue[i].position.getX(), queue[i].position.getY(), -5.0f);
					queue[i].dob.draw(gl);
				}
			}
		}
	}

	@Override
	public void onSurfaceChanged(GL10 gl, int width, int height) {
		if(height == 0) { 						//Prevent A Divide By Zero By
			height = 1; 						//Making Height Equal One
		}

		Log.v("Surface change", "Surface Change: " + width + ", " + height);
		
		gl.glViewport(0, 0, width, height); 	//Reset The Current Viewport
		gl.glMatrixMode(GL10.GL_PROJECTION); 	//Select The Projection Matrix
		gl.glLoadIdentity(); 					//Reset The Projection Matrix

		//Calculate The Aspect Ratio Of The Window
		GLU.gluPerspective(gl, 45.0f, (float)width / (float)height, 0.1f, 100.0f);

		gl.glMatrixMode(GL10.GL_MODELVIEW); 	//Select The Modelview Matrix
		gl.glLoadIdentity(); 					//Reset The Modelview Matrix
	}

	@Override
	public void onSurfaceCreated(GL10 gl, EGLConfig arg1) {
		gl.glShadeModel(GL10.GL_SMOOTH); 			//Enable Smooth Shading
		gl.glClearColor(0.0f, 0.0f, 0.0f, 0.5f); 	//Black Background
		gl.glClearDepthf(1.0f); 					//Depth Buffer Setup
		gl.glEnable(GL10.GL_DEPTH_TEST); 			//Enables Depth Testing
		gl.glDepthFunc(GL10.GL_LEQUAL); 			//The Type Of Depth Testing To Do
		
		//Really Nice Perspective Calculations
		gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST); 
		
	}
	
	public void setDrawQueue(RenderQueue.RenderableObject[] queue){
		this.queue = queue;
	}
	
	public synchronized void waitDrawingComplete(){
	}

}
